/*
 * Copyright 2013 University of Padua, Italy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package it.dei.unipd.healthservice.servlet;

import it.dei.unipd.healthservice.resource.*;
import it.dei.unipd.healthservice.database.*;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet per visionare le fabbriche
 * 
 * @author Nicola Salmaso
 * @version 1.00
 */
public class ViewRecapitiServlet extends AbstractDatabaseServlet {

	/**
	 * Visualizza tutte i recapiti.
	 * 
	 * @param req
	 *            la richiesta ricevuta dal client.
	 * @param res
	 *            la rispota fornita dal server.
	 * 
	 * @throws ServletException
	 *             se ci sono problemi nell'esecuzione della servlet.
	 * @throws IOException
	 *             se ci sono problemi nella comunicazione client-server.
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		
		Connection con = null;
		try {
			con = DS.getConnection();
			HttpSession session=req.getSession();
			String mail = (String)session.getAttribute("email");
			req.setAttribute("prova", mail);
			
			ArrayList<Recapito> recapiti = new ViewRecapitiDatabase(con,mail).search();
			//recapiti.add(new Recapito("rag1","stato","provincia","citta","indirizzo","cap"));
			req.setAttribute("recapiti", recapiti);
			Cliente cliente = new ViewClientiDatabase(con).getCliente(mail);
			req.setAttribute("cliente",cliente);
			/*
			ArrayList<Cliente> clienti = (ArrayList<Cliente>)new ViewClientiDatabase(con).search();
			for( Cliente c : clienti)
				if( c.getEmail().equals(mail)) req.setAttribute("cliente", c);
				*/
		} catch (NullPointerException e) {
			req.setAttribute("errore", "Impossibile creare la connessione al database.");		
		} catch (SQLException e) {
			req.setAttribute("errore", "Errore durante l'accesso al database:"+e.getMessage());
		}
		String address = "ViewProdottiCarrello";
		RequestDispatcher dispatcher = req.getRequestDispatcher(address);
		dispatcher.forward(req, res);
		
	}

}
